package com.btpj.hospital_server.exception;

import com.btpj.hospital_server.dto.CommonResult;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author BTPJ  2020/9/2
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CommonResult<Void> handleException(Exception e) {
        e.printStackTrace();
        // 校验不通过异常
        if (e instanceof BindException) {
            FieldError fieldError = ((BindException) e).getBindingResult().getFieldError();
            if (fieldError != null) {
                return CommonResult.error(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return CommonResult.error(e.getMessage());
    }

}
